package org.amos.feign.utils;

import cn.hutool.core.util.StrUtil;
import com.alibaba.csp.sentinel.slots.block.BlockException;
import com.alibaba.csp.sentinel.slots.block.degrade.DegradeException;
import feign.FeignException;
import feign.RetryableException;
import lombok.extern.slf4j.Slf4j;
import org.amos.core.basic.exception.ServiceException;
import org.amos.core.basic.vo.R;
import org.springframework.http.HttpStatus;

import java.util.Objects;

/**
 * feign 工具类
 */
@Slf4j
public class FeignUtil {
    /**
     * sentinel限流、熔断/openfeign相关异常提示
     * @param ex
     * @return
     */

    public static R<?> getR(Throwable ex) {
        // RetryableException 提示语
        String msg = StrUtil.EMPTY;
        if (ex instanceof RetryableException) {
            msg = "服务无响应，请稍后再试！";
        }
        if (ex instanceof FeignException) {
            msg = "服务崩溃了，请稍后再试！";
        }
        if (!BlockException.isBlockException(ex)) {
            return R.error(msg);
        }
        // 限流相关异常提示语
        msg = "当前排队人数较多，请稍后再试！";
        if (ex instanceof DegradeException) {
            msg = "当前系统繁忙，请稍后再试！";
        }
        return R.error(msg);
    }

    /**
     * 获取feign接口调用成功返回值
     * @param result
     * @return
     * @param <T>
     */
    public static <T> T getData(R<T> result) {
        if (Objects.isNull(result)) {
            throw new ServiceException("服务异常，请稍后再试！");
        }
        if (result.getCode() != HttpStatus.OK.value()) {
            throw new ServiceException(result.getMsg());
        }
        return result.getData();
    }

}
